package com.chen.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.dao.RoleDao;
import com.chen.dao.UserInfoDao;
import com.chen.entity.Menu;
import com.chen.entity.Role;
import com.chen.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class UserInfoServiceImpl extends ServiceImpl<RoleDao,Role>implements UserDetailsService {
    @Autowired
    RoleDao roleDao;
    @Autowired
    UserInfoDao userInfoDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //设置账号密码
        LambdaQueryWrapper<UserInfo>queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getUname,username);
        List<UserInfo> userInfos = userInfoDao.selectList(queryWrapper);
        if(userInfos.size()==0|| userInfos==null){
            throw new UsernameNotFoundException("账户不存在");
        }
        //从数据库中查询用户
        UserInfo tuser=userInfos.get(0);
        //从数据库中查询到该用户的所有角色（含权限）
        tuser.setRoles(roleDao.queryById(tuser.getId()));
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        //取出用户的角色，封装到authorities中
        for(Role role:tuser.getRoles()){
            authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
            for(Menu menu:role.getMenus()){ //如果权限精确到权限菜单级别，则要补充这个
                authorities.add(new SimpleGrantedAuthority(menu.getMpath()));
            }
        }
        //下面的密码一般要加密
        return new User(tuser.getUname(),new BCryptPasswordEncoder().encode(tuser.getPwd()),authorities);
    }
}
